// 根据RGB值估算色温
const calculateColorTemperature = (r, b) => {
  // 简化的色温计算，基于红蓝比例
  const rbRatio = r / b;
  if (rbRatio > 1.5) return 2700; // 暖色
  if (rbRatio < 0.8) return 6500; // 冷色
  return 4000; // 中性
};

// 生成补光建议
const generateSuggestions = (brightness, colorTemp) => {
  const suggestions = [];

  // 基于亮度的建议
  if (brightness < 50) {
    suggestions.push('光线严重不足，建议：');
    suggestions.push('- 使用主补光灯，亮度调至100%');
    suggestions.push('- 补光灯距离保持在0.5米左右');
    suggestions.push('- 使用反光板增加环境光');
  } else if (brightness < 100) {
    suggestions.push('光线偏暗，建议：');
    suggestions.push('- 使用补光灯，亮度调至60-80%');
    suggestions.push('- 补光灯距离保持在1米左右');
  } else if (brightness < 150) {
    suggestions.push('光线适中，建议：');
    suggestions.push('- 可使用柔光灯调节氛围');
    suggestions.push('- 补光灯亮度调至30-50%');
  } else {
    suggestions.push('光线充足，建议：');
    suggestions.push('- 可使用柔光布适当降低对比度');
    suggestions.push('- 注意控制高光区域');
  }

  // 基于色温的建议
  if (colorTemp < 3000) {
    suggestions.push('色温偏暖，建议：');
    suggestions.push('- 可使用冷色调补光提升层次感');
  } else if (colorTemp > 6000) {
    suggestions.push('色温偏冷，建议：');
    suggestions.push('- 可使用暖色调补光提升画面温度');
  }

  return suggestions;
};

export const analyzeLight = (file) => {
  return new Promise((resolve, reject) => {
    if (!file) {
      reject(new Error('未提供图片文件'));
      return;
    }

    const reader = new FileReader();
    
    reader.onload = (event) => {
      const img = new Image();
      img.crossOrigin = 'Anonymous';
      
      img.onload = () => {
        try {
          const canvas = document.createElement('canvas');
          canvas.width = img.width;
          canvas.height = img.height;
          const ctx = canvas.getContext('2d');
          ctx.drawImage(img, 0, 0);

          const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
          const data = imageData.data;
          let brightnessSum = 0;
          let rSum = 0, gSum = 0, bSum = 0;
          const distribution = new Array(256).fill(0);

          // 分析像素数据
          for (let i = 0; i < data.length; i += 4) {
            const r = data[i];
            const g = data[i + 1];
            const b = data[i + 2];
            
            // 计算亮度
            const brightness = Math.round((r + g + b) / 3);
            brightnessSum += brightness;
            distribution[brightness]++;
            
            // 累加RGB值用于计算色温
            rSum += r;
            gSum += g;
            bSum += b;
          }

          const pixelCount = data.length / 4;
          const avgBrightness = Math.round(brightnessSum / pixelCount);
          
          // 计算近似色温
          const rAvg = rSum / pixelCount;
          const bAvg = bSum / pixelCount;
          const colorTemp = Math.round(calculateColorTemperature(rAvg, bAvg));

          // 生成分析结果
          const result = {
            brightness: avgBrightness,
            colorTemp: colorTemp,
            distribution: distribution.map((count, index) => ({
              brightness: index,
              count: count / pixelCount * 100 // 转换为百分比
            })),
            suggestions: generateSuggestions(avgBrightness, colorTemp)
          };

          resolve(result);
        } catch (error) {
          reject(new Error('图片分析过程中出错：' + error.message));
        }
      };

      img.onerror = () => {
        reject(new Error('图片加载失败'));
      };

      img.src = event.target.result;
    };

    reader.onerror = () => {
      reject(new Error('文件读取失败'));
    };

    reader.readAsDataURL(file);
  });
};